import React, { useEffect, useState, useRef } from 'react'
import { Button, Tabs, App, Card, Form, Row, Col, Alert, Spin } from 'antd'
import { useModel } from 'umi'
import FormList from '../../components/FormList/FormList'
import RateList from './RateList'
import CITY from '@/utils/city.json'
import { getUnique } from '@/utils/utils'

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 20 }
}

export default () => {
  const { GetBasicsInfo, UpdateShopInfo, GetQrcode, UpdateAlipayInfo, SaveSignInfo, SaveShopRentRate } =
    useModel('Merchant')
  const { scopeSets } = useModel('Global')
  const { message } = App.useApp()

  const [tabItem, setTabItem] = useState([])
  const [tabActiveKey, setTabActiveKey] = useState('baseInfo')
  const [baseInfo, setBaseInfo] = useState({})
  const [qrcode, setQrcode] = useState(null)
  const [baseInfoFormRef] = Form.useForm()
  const [bindingInfoFormRef] = Form.useForm()
  const [contractConfigFormRef] = Form.useForm()
  const [rateConfigFormRef] = Form.useForm()
  const [originFormData, setOriginFormData] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  const baseInfoData = useRef({})

  useEffect(() => {
    setOriginFormData(formDataList)
  }, [baseInfo])
  const formDataList = {
    baseInfo: [
      {
        title: '店铺名称',
        type: 'input',
        formProp: {
          name: 'shop_name',
          label: '店铺名称',
          rules: [{ required: true, message: '请输入店铺名称！' }]
        },
        itemProp: {
          placeholder: '请输入店铺名称',
          style: { width: '346px' }
        }
      },
      {
        title: '企业名称',
        type: 'input',
        formProp: {
          name: 'corporate_name',
          label: '企业名称',
          rules: [{ required: true, message: '请输入企业名称！' }]
        },
        itemProp: {
          placeholder: '请输入企业名称',
          style: { width: '346px' }
        }
      },
      {
        title: '联系人',
        type: 'input',
        formProp: {
          name: 'store_contact',
          label: '联系人',
          rules: [{ required: true, message: '请输入联系人！' }]
        },
        itemProp: {
          placeholder: '请输入联系人',
          style: { width: '346px' }
        }
      },
      {
        title: '联系电话',
        type: 'input',
        formProp: {
          name: 'contact_tel',
          label: '联系电话',
          rules: [{ required: true, message: '请输入联系电话！' }]
        },
        itemProp: {
          placeholder: '请输入联系电话',
          style: { width: '346px' }
        }
      },
      {
        title: '企业地址',
        type: 'cascader',
        formProp: {
          name: 'enterpriseAddress',
          label: '企业地址',
          rules: [{ required: true, message: '请选择企业地址！' }]
        },
        itemProp: {
          placeholder: '请选择企业地址！',
          options: CITY,
          style: { width: '346px' }
        }
      },
      {
        title: '联系地址',
        type: 'input',
        formProp: {
          name: 'company_detail_address',
          label: '联系地址',
          rules: [{ required: true, message: '请输入联系地址！' }]
        },
        itemProp: {
          placeholder: '请输入联系地址',
          style: { width: '346px' }
        }
      },
      {
        title: '营业执照号',
        type: 'input',
        formProp: {
          name: 'reg_no',
          label: '营业执照号',
          rules: [{ required: true, message: '请输入营业执照号！' }]
        },
        itemProp: {
          placeholder: '请输入营业执照号',
          style: { width: '346px' }
        }
      },
      {
        title: '法人姓名',
        type: 'input',
        formProp: {
          name: 'legal_person_name',
          label: '法人姓名',
          rules: [{ required: true, message: '请输入法人姓名！' }]
        },
        itemProp: {
          placeholder: '请输入法人姓名',
          style: { width: '346px' }
        }
      },
      {
        title: '法人身份证号',
        type: 'input',
        formProp: {
          name: 'legal_person_id_num',
          label: '法人身份证号',
          rules: [{ required: true, message: '请输入法人身份证号！' }]
        },
        itemProp: {
          placeholder: '请输入法人身份证号',
          style: { width: '346px' }
        }
      },
      {
        title: '营业执照',
        type: 'upload',
        formProp: {
          label: '营业执照',
          name: 'license_pic',
          required: true,
          text: '上传',
          maxCount: 1
        }
      },
      {
        title: '法人身份证正面',
        type: 'upload',
        formProp: {
          label: '法人身份证正面',
          name: 'legal_person_front_card_pic',
          required: true,
          text: '上传',
          maxCount: 1
        }
      },
      {
        title: '法人身份证背面',
        type: 'upload',
        formProp: {
          label: '法人身份证背面',
          name: 'legal_person_back_card_pic',
          required: true,
          text: '上传',
          maxCount: 1
        }
      }
    ],
    bindingInfo: [
      {
        title: '支付宝姓名',
        type: 'input',
        formProp: {
          name: 'alipay_name',
          label: '支付宝姓名',
          rules: [{ required: true, message: '请输入支付宝姓名！' }]
        },
        itemProp: {
          placeholder: '请输入支付宝姓名',
          style: { width: '346px' }
        }
      },
      {
        title: '支付宝账号',
        type: 'input',
        formProp: {
          name: 'alipay_account',
          label: '支付宝账号',
          rules: [{ required: true, message: '请输入支付宝账号！' }]
        },
        itemProp: {
          placeholder: '请输入支付宝账号',
          style: { width: '346px' }
        }
      }
    ],
    contractConfig: [
      {
        title: '合同默认签署地',
        type: 'cascader',
        formProp: {
          name: 'address',
          label: '合同默认签署地',
          rules: [{ required: true, message: '请输入合同默认签署地！' }],
          help: '合同协议的默认签署地区'
        },
        itemProp: {
          placeholder: '请输入合同默认签署地',
          options: CITY,
          style: { width: '346px' },
          onChange: e => {
            if (e) {
              contractConfigFormRef.setFieldValue('court_name', `${e.join('')}人民法院`)
            } else {
              contractConfigFormRef.setFieldValue('court_name', '')
            }
          }
        }
      },
      {
        title: '合同约定诉讼法院',
        type: 'input',
        formProp: {
          name: 'court_name',
          label: '合同约定诉讼法院',
          rules: [{ required: true, message: '请输入合同约定诉讼法院！' }],
          help: '合同履行过程中发生争议，协商不成后的诉讼法院'
        },
        itemProp: {
          placeholder: '请输入合同约定诉讼法院',
          style: { width: '346px' }
        }
      }
    ],
    rateConfig: [
      {
        title: '分期利率配置',
        type: 'component',
        formProp: {
          name: 'rate_config',
          label: '分期利率配置'
        },
        component: <RateList form={rateConfigFormRef} data={baseInfo}></RateList>
      }
    ]
  }

  const handleBaseInfoFinished = async e => {
    const { enterpriseAddress } = e
    const params = {
      ...e
    }
    if (enterpriseAddress?.length) {
      params.company_province = enterpriseAddress[0]
      params.company_city = enterpriseAddress[1]
      params.company_area = enterpriseAddress[2]
    }

    const res = await UpdateShopInfo(params)
    if (res) {
      message.success('修改成功')
    }
  }

  const handleBindingInfoFinished = async e => {
    const params = {
      ...e
    }

    const res = await UpdateAlipayInfo(params)
    if (res) {
      message.success('修改成功')
    }
  }

  const handleContractConfigFinished = async e => {
    const { address } = e
    const params = {
      ...e
    }
    params.sign_address = address.join('')
    params.province = address[0]
    params.city = address[1]
    params.area = address[2]

    const res = await SaveSignInfo(params)
    if (res) {
      message.success('修改成功')
    }
  }

  const handleRateConfigFinished = async e => {
    const { rate_list } = e
    const params = {
      rate_list: {}
    }
    Object.keys(rate_list).forEach(i => {
      params.rate_list[i] = (rate_list[i] / 100).toFixed(4)
    })
    const res = await SaveShopRentRate(params)
    if (res) {
      message.success('修改成功')
    }
  }

  const downQR = () => {
    //下载图片地址和图片名
    const image = new Image()
    // 解决跨域 Canvas 污染问题
    image.setAttribute('crossOrigin', 'anonymous')
    image.onload = function () {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, image.width, image.height)
      const url = canvas.toDataURL('image/png') //得到图片的base64编码数据

      const a = document.createElement('a') // 生成一个a元素
      const event = new MouseEvent('click') // 创建一个单击事件
      a.download = 'QRCode' // 设置图片名称
      a.href = url // 将生成的URL设置为a.href属性
      a.dispatchEvent(event) // 触发a的单击事件
    }
    image.src = qrcode.alipay_open_app_qrcode_create_response.qr_code_url
  }

  const originTabItem = [
    {
      key: 'baseInfo',
      label: '基础信息',
      children: (
        <Spin tip='加载中...' spinning={isLoading}>
          <Card bordered={false} style={{ boxShadow: 'none' }}>
            <Form
              form={baseInfoFormRef}
              name=''
              {...formItemLayout}
              onFinish={handleBaseInfoFinished}
              initialValues={baseInfo}
            >
              <FormList list={originFormData.baseInfo}></FormList>
            </Form>
            <Row>
              <Col offset={10}>
                <Button type='primary' onClick={baseInfoFormRef.submit}>
                  修改
                </Button>
              </Col>
            </Row>
          </Card>
        </Spin>
      )
    },
    {
      key: 'bindingInfo',
      label: '提现绑定信息',
      children: (
        <Spin tip='加载中...' spinning={isLoading}>
          <Card bordered={false} style={{ boxShadow: 'none' }} title='支付宝信息'>
            <Form
              form={bindingInfoFormRef}
              name=''
              {...formItemLayout}
              onFinish={handleBindingInfoFinished}
              initialValues={baseInfo}
            >
              <FormList list={originFormData.bindingInfo}></FormList>
            </Form>
            <Row>
              <Col offset={10}>
                <Button type='primary' onClick={bindingInfoFormRef.submit}>
                  修改
                </Button>
              </Col>
            </Row>
          </Card>
        </Spin>
      )
    },
    {
      key: 'QRcode',
      label: '店铺二维码',
      children: (
        <Spin tip='加载中...' spinning={isLoading}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', minHeight: '100px' }}>
            {isLoading ? null : qrcode?.alipay_open_app_qrcode_create_response?.qr_code_url ? (
              <>
                <img src={qrcode.alipay_open_app_qrcode_create_response.qr_code_url}></img>
                <Button type='primary' style={{ marginTop: '20px' }} onClick={() => downQR()}>
                  下载二维码
                </Button>
              </>
            ) : (
              <Button type='primary' onClick={() => getQrcode()}>
                重新获取
              </Button>
            )}
          </div>
        </Spin>
      )
    },
    {
      key: 'contractConfig',
      label: '合同配置',
      children: (
        <Spin tip='加载中...' spinning={isLoading}>
          <Card bordered={false} style={{ boxShadow: 'none' }} title='合同配置'>
            <Form
              form={contractConfigFormRef}
              name=''
              {...formItemLayout}
              onFinish={handleContractConfigFinished}
              initialValues={baseInfo}
            >
              <FormList list={originFormData.contractConfig}></FormList>
            </Form>
            <Row>
              <Col offset={10}>
                <Button type='primary' onClick={contractConfigFormRef.submit}>
                  修改
                </Button>
              </Col>
            </Row>
          </Card>
        </Spin>
      )
    }
  ]

  const getInfo = async () => {
    setIsLoading(true)
    const res = await GetBasicsInfo()
    setIsLoading(false)
    baseInfoData.current = res
    const initialValues = { ...res }
    const { rent_rate_list, company_area, company_city, company_province, province, city, area } = res

    if (company_area && company_city && company_province) {
      initialValues.enterpriseAddress = [company_province, company_city, company_area]
    }

    if (province && city && area) {
      initialValues.address = [province, city, area]
    }

    if (rent_rate_list) {
      const newRateData = {}
      Object.keys(rent_rate_list).forEach(i => {
        newRateData[i] = (rent_rate_list[i] * 100).toFixed(2)
      })
      initialValues.rate_list = newRateData
    }
    setBaseInfo(initialValues)

    baseInfoFormRef.setFieldsValue(initialValues)
    bindingInfoFormRef.setFieldsValue(initialValues)
    contractConfigFormRef.setFieldsValue(initialValues)
  }

  const getQrcode = async () => {
    setIsLoading(true)
    const res = await GetQrcode()
    setIsLoading(false)
    if (res) {
      setQrcode(res)
    } else {
      setQrcode(null)
    }
  }

  const handleChangeTab = key => {
    setIsLoading(false)
    setTabActiveKey(key)
  }

  useEffect(() => {
    if (tabActiveKey === 'QRcode') {
      getQrcode()
    } else {
      getInfo()
    }
  }, [tabActiveKey])

  useEffect(() => {
    const tabList = [...originTabItem]
    if (scopeSets.includes('user_create_order')) {
      const extraTab = {
        key: 'rateConfig',
        label: '利率配置',
        children: (
          <Card bordered={false} style={{ boxShadow: 'none' }}>
            <Alert
              banner
              message='利率对应用户总租金的百分比(最高不超过30%)，例如10%指的是总租金的利息为10个点'
              type='info'
              showIcon
            />
            <Form
              form={rateConfigFormRef}
              name=''
              {...formItemLayout}
              onFinish={handleRateConfigFinished}
              initialValues={baseInfo}
            >
              <FormList list={originFormData.rateConfig}></FormList>
            </Form>
            <Row>
              <Col offset={10}>
                <Button type='primary' onClick={rateConfigFormRef.submit}>
                  修改
                </Button>
              </Col>
            </Row>
          </Card>
        )
      }
      tabList.push(extraTab)
    }
    setTabItem(tabList)
  }, [scopeSets, originFormData, qrcode, isLoading])

  return (
    <Card>
      <Tabs defaultActiveKey='baseInfo' items={tabItem} onChange={handleChangeTab}></Tabs>
    </Card>
  )
}
